class WebSite < ActiveRecord::Base
  include HTTParty
  base_uri 'www.jagajx.com'
  #debug_output $stdout

  attr_accessor :cookie, :base_params, :teachers

  def initialize
    @teachers = []
  end

  def login
    reset_persist_file
    unless persist?
      resp = self.class.post('/pfs/dr_wsyy/post?a=ksyy', body: {dlxx: '430521198705250305', dlmm: '15207495822', ev: 'dl', parm: ''})
      # ><script type=\"text/javascript\" >window.location.href='/pfs/dr_coaches?titem=03&jljzlx=37&listview=wsyy';</script>
      @base_params = resp.body.split('?')[1].split("'")[0]
      @cookie = resp.headers['set-cookie']
      persist
    end
    self
  end

  def split_symbol
    '||||'
  end

  def persist
    File.open(login_file_status, 'w') { |io| io.write("#{@cookie}#{split_symbol}#{@base_params}") }
  end

  def persist?
    File.exist?(login_file_status)
  end

  def reset_persist_file
    return unless File.exist?(login_file_status)
    if (File.ctime(login_file_status) - Time.now).abs > 1.hours
      File.delete(login_file_status)
    else
      @cookie, @base_params = File.open(login_file_status).read.split(split_symbol)
    end
  end

  def login_file_status
    './login_file.status'
  end

  def teachers
    resp = self.class.get('/pfs/dr_coaches/CDefault?' + @base_params, headers: {'Cookie' => @cookie})
    doc = Nokogiri::HTML(resp.body)
    doc.css('.style1 li').each do |li|
      spans = li.css('span')
      @teachers << Teacher.new('http://www.jagajx.com/pfs/' + li.at_css('a')['href'], spans[0].text.strip, spans[2].text.strip, @cookie)
    end
    @teachers
  end

  def teacher(name)
    teachers if @teachers.size <= 0
    @teachers.select { |t| t.name == name }.first
  end

  # 预定某一名老师的课程
  def make_appoint(name)
    points = detact_appoints(name)
    flag = false
    logger.info("Total Find #{points.size} appoints.")
    points.each do |point|
      break if flag
      flag = point.do_appoint
      Notify.success_apoint(name, point).deliver if flag
    end
    flag
  end

  def detact_appoints(name)
    teacher = self.teacher(name)
    teacher.morning_points + teacher.afternoon_points
  end

end
